from django.shortcuts import render

# Create your views here.
from django.http import HttpResponseRedirect,HttpResponse
from django.shortcuts import render

from django.contrib.auth.models import User
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required

def register_view(request):
    if request.method=="GET":
        return request(request,"register.html")
    elif request.method=="POST":
        username=request.POST['username']
        password_1=request.POST['password_1']
        password_2=request.POST["password_2"]
        if password_1!=password_2:
            return HttpResponse('---两次密码输入不一致---')

        user=User.objects.create_user(username=username,password=password_1)
        return HttpResponseRedirect('/login')

def login_view(request):
    if request.method=="GET":
        return render(request,"login.html")
    elif request.method=="POST":
        username=request.POST['username']
        password=request.POST['password']

        user=authenticate(username=username,password=password)
        if not user:
            return HttpResponse("---密码错误—--")
        else:
            login(request,user)
            return HttpResponseRedirect('/index')

def logout_view(request):
    logout(request)
    return HttpResponse("---已退出")

@login_required
def index_view(request):
    # login_required 的修饰器要在settings.LOGIN_URL
    user=request.user
    return HttpResponse('登录成功')





